package uk.ac.aber.paws.client.net;

import java.util.logging.Level;
import java.io.*;

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

import uk.ac.aber.paws.client.core.Initiator;
import uk.ac.aber.paws.client.core.PAWSClient;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 16th August 2011
 * 
 * ServerSocketListener.java
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class ServerSocketListener {

	private SSLServerSocket secureServerSocket;
	
	/**
	 * This procedure invokes a ServerSocket on the port specified by app.main.net.servercommsport in the config.properties file. It 
	 * listens on this port for a connection from the calling server. Once a message is receieved, the required action is invoked
	 * by this client.
	 * @param monitorObj Information about the session
	 */
	public ServerSocketListener(boolean secure) {
		
		try {
			
			if (secure) {
				Initiator.LOG_FILE.log(Level.CONFIG,"Secure Server Socket configured to listen on port: "+PAWSClient.getConfig().getProperty("app.main.net.secureservercommsport"));
				
				SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
			    secureServerSocket = (SSLServerSocket)ssf.createServerSocket(Integer.parseInt(PAWSClient.getConfig().getProperty("app.main.net.secureservercommsport")));
			    final String[] enabledCipherSuites = { "SSL_DH_anon_WITH_RC4_128_MD5" };
			    secureServerSocket.setEnabledCipherSuites(enabledCipherSuites);
			    
				Initiator.LOG_FILE.log(Level.CONFIG,"Secure Server now waiting for connections: "+secureServerSocket.toString());
				
				initiateSecureServer();
			}
			
		}
		catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * Waits for the connection and then acts on it by instantiating ConnectionHandler to deal with the request.
	 */
	private void initiateSecureServer() {
	
		while (true) {
			
			try {
				SSLSocket socket = (SSLSocket)secureServerSocket.accept();
				new SecureConnectionHandler(socket);
			}
			catch (IOException ex) {
				Initiator.LOG_FILE.log(Level.ALL,ex.toString());
				ex.printStackTrace();
			}
		}
	}
}
